home *** CD-ROM | disk | FTP | other *** search
/ HyperLib 1997 Winter - Disc 1 / HYPERLIB-1997-Winter-CD1.ISO.7z / HYPERLIB-1997-Winter-CD1.ISO / オンラインウェア / BUS / TMCM Software and Labs.sit / Software for TMCM 7_95 / Files for Lab 13 / Synchronized Random Walk < prev    next >
Text File  |  1995-07-07  |  2KB  |  58 lines

  1. {
  2.    This program illustrates the use of a shared variable
  3.    for communication between processes.  The value of a
  4.    shared variable, angle, is computed by one process
  5.    but is used by every process.  A second shared variable,
  6.    control, is used to control access to angle.
  7.  
  8.    A GRAB statement is used to create a critical region.
  9.    Only one process can be in this region at any given
  10.    time.  This means that only one process can have 
  11.    access to the shared variable angle at any give time.
  12. }
  13.  
  14.  
  15. DECLARE angle    { Shared variable used for communication
  16.                    among the turtles.  The value of angle
  17.                    is set by Turtle #1.  Both turtles use
  18.                    the value of angle to decide which 
  19.                    direction to face at each step of the 
  20.                    random walk. }
  21.  
  22. DECLARE control  { Shared variable used to control
  23.                    communication among the turtles.
  24.                    A turtle is allowed to access the
  25.                    shared variable, angle, only if
  26.                    the value of control is equal to the
  27.                    ForkNumber of that turtle. }
  28.  
  29. control := 1   { This says that it is Turtle #1's turn
  30.                  to access the shared variable, angle. }
  31.  
  32. fork(2)  { Split into two turtles.  Turtle #1 has a
  33.            ForkNumber = 1, while Turtle #2 has a
  34.            ForkNumber = 2. }
  35.  
  36. PenUp
  37. face(180*ForkNumber)  { Turtle #1 faces left; Turtle #2 faces right }
  38. forward(4)
  39. PenDown
  40.  
  41. LOOP
  42.    IF ForkNumber = control THEN  { Test whether it's this turtle's turn. }
  43.       GRAB control THEN      { Begin critical region. }
  44.          IF ForkNumber = 1 THEN
  45.             angle := randomInt(360)  { Turtle #1 generates a }
  46.             face(angle)              { value for angle and uses it. }
  47.             forward(1)
  48.             control := 2  { Says it's Turtle #2's turn next. }
  49.          ELSE
  50.             face(angle)    { Turtle #2 just uses the value of angle. }
  51.             forward(1)
  52.             control := 1  { Says it's Turtle #1's turn next. }
  53.          END IF
  54.       END GRAB              { End critical region. }
  55.    END IF
  56.    EXIT IF 1=2  { loop never ends }
  57. END LOOP
  58.